package com.example.my.agiftthat.ui.home.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.ScrollView;

import com.example.my.agiftthat.MvpActivity.ClickActivity;
import com.example.my.agiftthat.MvpActivity.LoginActivity;
import com.example.my.agiftthat.R;
import com.example.my.agiftthat.config.Url;
import com.example.my.agiftthat.helper.DividerItemDecoration;
import com.example.my.agiftthat.helper.GlideImageLoader;
import com.example.my.agiftthat.helper.OkHttpClientHelper;
import com.example.my.agiftthat.helper.decoration.SpacesItemDecoration;
import com.example.my.agiftthat.ui.home.adapter.LowRecyclerAdapter;
import com.example.my.agiftthat.ui.home.adapter.SixRecyclerAdapter;
import com.example.my.agiftthat.ui.home.bean.BannerBean;
import com.example.my.agiftthat.ui.home.bean.LowBean;
import com.example.my.agiftthat.ui.home.bean.SixBean;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerClickListener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by My on 2016/12/3.
 */

public class SelectorFragment extends Fragment {
    private Context mContext = null;
    private Banner banner_home;
    private List<BannerBean.DataBean.BannersBean> bList = new ArrayList<>();
    private RecyclerView recyclerView_six, recyclerView_low;
    private PullToRefreshScrollView pullToRefreshScrollView_selector;
    private List<String> bList_imageUrl = new ArrayList<>();
    private List<SixBean.DataBean.SecondaryBannersBean> sList = new ArrayList<>();
    private List<LowBean.DataBean.ItemsBean> lList = new ArrayList<>();
    private LowRecyclerAdapter lowRecyclerAdapter = null;
    private int curPage = 1;
    private String url = "";
    private Intent intent=null;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    bList = (List<BannerBean.DataBean.BannersBean>) msg.obj;
                    for (int i = 0; i < bList.size(); i++) {
                        bList_imageUrl.add(bList.get(i).getImage_url());
                    }
                    banner_home.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
                    banner_home.setImageLoader(new GlideImageLoader());
                    //设置图片集合
                    banner_home.setImages(bList_imageUrl);
                    //设置自动轮播 默认为true
                    banner_home.isAutoPlay(true);
                    //设置轮播时间
                    banner_home.setDelayTime(2000);
                    //设置指示器位置（当banner模式中有指示器时）
                    banner_home.setIndicatorGravity(BannerConfig.CENTER);
                    //banner设置方法全部调用完毕时最后调用
                    banner_home.start();
                    break;
            }
        }
    };
    private Handler handler1 = new Handler() {
        @Override
        public void handleMessage(Message msg1) {
            super.handleMessage(msg1);
            switch (msg1.what) {
                case 1:
                    sList = (List<SixBean.DataBean.SecondaryBannersBean>) msg1.obj;
                    recyclerView_six.setHasFixedSize(true);
                    recyclerView_six.setLayoutManager(new GridLayoutManager(mContext, 3));
                    SixRecyclerAdapter adapter = new SixRecyclerAdapter(mContext, sList);
                    recyclerView_six.setAdapter(adapter);
                    break;
            }
        }
    };
    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg2) {
            super.handleMessage(msg2);
            switch (msg2.what) {
                case 2:
                    lList = (List<LowBean.DataBean.ItemsBean>) msg2.obj;
                    if (curPage == 1) {
                        lowRecyclerAdapter.reloadRecyclerView(lList, true);
                    } else {
                        lowRecyclerAdapter.reloadRecyclerView(lList, false);
                    }
                    pullToRefreshScrollView_selector.onRefreshComplete();
                    break;
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        reloadNetworkData();
        reloadNetworkData1();
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_selector, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        banner_home = (Banner) view.findViewById(R.id.banner_home);
        recyclerView_six = (RecyclerView) view.findViewById(R.id.recyclerView_six);
        recyclerView_low = (RecyclerView) view.findViewById(R.id.recyclerView_low);

        banner_home.setOnBannerClickListener(new OnBannerClickListener() {
            @Override
            public void OnBannerClick(int position) {
                if((bList.get(position).getTarget_id()+"")==null){
                    intent=new Intent(getActivity(), LoginActivity.class);
                    startActivity(intent);
                }else {
                    intent=new Intent(getActivity(),ClickActivity.class);
                    int target_id=bList.get(position).getTarget_id();
                    intent.putExtra("target_id",target_id);
                    startActivity(intent);
                }
            }
        });
        pullToRefreshScrollView_selector = (PullToRefreshScrollView) view.findViewById(R.id.pullToRefreshScrollView_selector);
        pullToRefreshScrollView_selector.setMode(PullToRefreshBase.Mode.BOTH);
        pullToRefreshScrollView_selector.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                curPage = 1;
                reloadNetworkData1();
                pullToRefreshScrollView_selector.onRefreshComplete();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                curPage++;
                reloadNetworkData1();
            }
        });
//        Log.i("tag","++++++++++++++++++++++");
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        recyclerView_low.setHasFixedSize(true);
        recyclerView_low.setLayoutManager(new LinearLayoutManager(mContext));
        lowRecyclerAdapter = new LowRecyclerAdapter(mContext, lList);
        recyclerView_low.setAdapter(lowRecyclerAdapter);
    }

    private void reloadNetworkData1() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String jsonStr = OkHttpClientHelper.getStringFromURL(mContext, Url.SELECTOR_LOW, 3);
                    Gson gson = new Gson();
                    LowBean lowBean = gson.fromJson(jsonStr, LowBean.class);
                    lList = lowBean.getData().getItems();
                    Message msg2 = new Message();
                    msg2.what = 2;
                    msg2.obj = lList;
                    handler2.sendMessage(msg2);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private void reloadNetworkData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String jsonString = OkHttpClientHelper.getStringFromURL(mContext,
                            Url.HOME_VP, 1);
                    String json = OkHttpClientHelper.getStringFromURL(mContext, Url.SELECTOR_SIX, 2);
                    Gson gson = new Gson();
                    BannerBean bannerBean = gson.fromJson(jsonString, BannerBean.class);
                    SixBean sixBean = gson.fromJson(json, SixBean.class);
                    List<BannerBean.DataBean.BannersBean> beanList = bannerBean.getData().getBanners();
                    List<SixBean.DataBean.SecondaryBannersBean> sixList = sixBean.getData().getSecondary_banners();
                    Message msg = new Message();
                    msg.what = 0;
                    msg.obj = beanList;
                    handler.sendMessage(msg);

                    Message msg1 = new Message();
                    msg1.what = 1;
                    msg1.obj = sixList;
                    handler1.sendMessage(msg1);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}
